package cn.schoolwow.quickdao.module.database.dql.response.flow.common.resultSet;

import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.reflection.QueryReflection;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.List;

public class MatchClazzFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        shouldMatch(flowContext);
        matchClazz(flowContext);
    }

    @Override
    public String name() {
        return "匹配用户指定类型";
    }

    private void shouldMatch(FlowContext flowContext){
        Class clazz = (Class) flowContext.getData("clazz");
        if(null==clazz){
            flowContext.log("自定义类不存在!跳过根据自定义类设置字段类型");
            flowContext.brokenCurrentFlow("");
        }
        String className = clazz.getName();
        if(className.startsWith("java.")){
            flowContext.log("类名属于java核心包!当前类名:"+className);
            flowContext.brokenCurrentFlow("");
        }
        Property[] resultSetPropertyArray = (Property[]) flowContext.checkData("resultSetPropertyArray");

        if(JSONObject.class.getName().equalsIgnoreCase(className)){
            resultSetPropertyArray[0].clazz = JSONObject.class;
            flowContext.brokenCurrentFlow("");
        }
        if(JSONArray.class.getName().equalsIgnoreCase(className)){
            resultSetPropertyArray[0].clazz = JSONArray.class;
            flowContext.brokenCurrentFlow("");
        }
    }

    private void matchClazz(FlowContext flowContext){
        Class clazz = (Class) flowContext.checkData("clazz");
        Property[] resultSetPropertyArray = (Property[]) flowContext.checkData("resultSetPropertyArray");

        //查询所有父类字段
        List<Field> fieldList = QueryReflection.newQuery(clazz)
                .execute()
                .getFieldList();
        for(Field field:fieldList){
            for(Property resultSetProperty:resultSetPropertyArray){
                if(resultSetProperty.columnLabel.equalsIgnoreCase(field.getName())){
                    resultSetProperty.clazz = field.getType();
                    break;
                }
            }
        }
    }
}
